How to catch Entity Framework Errors C#

43

How to catch Entity Framework Errors C# -

using System.Data.Entity.Validation;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using System.Data.Entity.Core;


public List<vwProduct> GetProductsByOffer(long offerId)
        {
            List<vwProduct> products = null;
            try
            {
                using (var context = new Entities())
                {
                    var query = from c in context.vwProduct
                                join o in context.tbOfferProduct on c.ProductId equals o.ProductId
                                where (o.OfferId == offerId)
                                select c;
                    products = query.ToList<vwProduct>();
                }
            }
    catch (DbEntityValidationException e)
    {
        StringBuilder strErr = new StringBuilder();
        foreach (var eve in e.EntityValidationErrors)
        {
        strErr.Append($"Entity of type {eve.Entry.Entity.GetType().Name}" +
        $"in the state {eve.Entry.State} "+
        $"has the following validation errors:");
        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}," +
                $" Error: {ve.ErrorMessage}");
        }
        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}, " +
                $"Value: {eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName)}," +
                $" Error: {ve.ErrorMessage}");
        }
        }
        ErrorDTO.TrackError("AddProduct", strErr.ToString());
    }
    catch (DbUpdateException ex)
    {
        ErrorDTO.TrackError(ex.Source, ex.InnerException);
    }
    catch (EntityCommandExecutionException cex)
    {
        ErrorDTO.TrackError(cex.InnerException);
    }
    catch (Exception ex)
    {
        ErrorDTO.TrackError(ex);
    }
    return products;
        }
		

Comments

Submit
0 Comments